package com.wss.lsl.lucene.demo.shipin.advanced.query;

import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.OpenBitSet;

///**
// * 自定义filter
// * 
// * @author lenovo
// * 
// */
//public class MyIDFilter extends Filter {
//
//	private String[] delIds = new String[] { "0", "3", "5", "6", "7" };
//
//	/**
//	 * 
//	 */
//	private static final long serialVersionUID = 3548332655789636374L;
//
//	@Override
//	public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
//		OpenBitSet ops = new OpenBitSet(reader.maxDoc());
//		// 将所有doc填满
//		ops.set(0, reader.maxDoc());
//		int[] docs = new int[1];
//		int[] freqs = new int[1];
//		for (String id : delIds) {
//			TermDocs tds = reader.termDocs(new Term("id", id));
//			int count = tds.read(docs, freqs);
//			if (count == 1) {
//				ops.clear(docs[0]);// 过滤点指定的doc
//			}
//		}
//		return ops;
//	}
//
//}

/**
 * 自定义filter的合理设计
 * 
 * @author lenovo
 * 
 */
public class MyIDFilter extends Filter {

	private String[] delIds = new String[] { "0", "3", "5", "6", "7" };
	private FilterAccessor filterAccessor;

	public MyIDFilter(FilterAccessor filterAccessor) {
		this.filterAccessor = filterAccessor;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 3548332655789636374L;

	@Override
	public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
		OpenBitSet ops = new OpenBitSet(reader.maxDoc());
		if (filterAccessor.set()) {
			set(reader, ops);
		} else {
			clear(reader, ops);
		}
		return ops;
	}

	private void set(IndexReader reader, OpenBitSet obs) {
		try {
			int[] docs = new int[1];
			int[] freqs = new int[1];
			String field = filterAccessor.getField();
			for (String id : filterAccessor.values()) {
				TermDocs tds = reader.termDocs(new Term(field, id));
				int count = tds.read(docs, freqs);
				if (count == 1) {
					obs.set(docs[0]);//
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void clear(IndexReader reader, OpenBitSet obs) {
		// 将所有doc填满
		try {
			obs.set(0, reader.maxDoc());
			int[] docs = new int[1];
			int[] freqs = new int[1];
			String field = filterAccessor.getField();
			for (String id : filterAccessor.values()) {
				TermDocs tds = reader.termDocs(new Term(field, id));
				int count = tds.read(docs, freqs);
				if (count == 1) {
					obs.clear(docs[0]);// 过滤点指定的doc
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
